﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace Brjnk.GpxExplorer.Localization
{
    /// <summary>
    /// Interaction logic for LocalizationTool.xaml
    /// </summary>
    public partial class LocalizationTool : Window
    {
        public LocalizationTool()
        {
            windowsRO = new System.Collections.ObjectModel.ReadOnlyObservableCollection<Window>(windows);
            stringsRO = new ReadOnlyObservableCollection<LocalizationString>(strings);

            InitializeComponent();
        }

        private System.Windows.Threading.DispatcherTimer tmr = new System.Windows.Threading.DispatcherTimer();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Closing += new CancelEventHandler(LocalizationTool_Closing);

            tmr.Interval = TimeSpan.FromSeconds(4);
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();

            RefreshWindowsList();
        }

        private void LocalizationTool_Closing(object sender, CancelEventArgs e)
        {
            LocalizationManager.Instance.SaveChanges();
            tmr.Stop();
            foreach (Window w in this.windows)
                w.PreviewMouseDown -= new MouseButtonEventHandler(w_MouseDown);
        }

        private void tmr_Tick(object sender, EventArgs e)
        {
            RefreshWindowsList();
        }

        private void RefreshWindowsList()
        {
            foreach (Window w in Application.Current.Windows)
            {
                if (!windows.Contains(w))
                {
                    windows.Add(w);
                    w.PreviewMouseDown += new MouseButtonEventHandler(w_MouseDown);
                }
            }

            for (int i = 0; i < this.windows.Count; i++)
            {
                var w = this.windows[i];
                if (!Application.Current.Windows.Cast<Window>().Contains(w))
                {
                    w.PreviewMouseDown -= new MouseButtonEventHandler(w_MouseDown);
                    windows.Remove(w);
                }
            }
        }

        private void w_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
            {
                e.Handled = true;
                try
                {
                    FindLocalizedStrings((DependencyObject)e.OriginalSource);
                }
                catch { }
            }
        }

        private void FindLocalizedStrings(DependencyObject element)
        {
            strings.Clear();
            while (element != null)
            {
                BrowseElement(element);
                element = VisualTreeHelper.GetParent(element);
            }
        }

        private void BrowseElement(DependencyObject element)
        {
            Type t = element.GetType();
            var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
                .Where(f => f.FieldType.IsAssignableFrom(typeof(DependencyProperty)));

            foreach (var f in fields)
            {
                var dependencyProperty = (DependencyProperty)f.GetValue(element);
                var binding = BindingOperations.GetBinding(element, dependencyProperty);
                if (!ProcessSimpleBinding(binding, element))
                {
                    var multiBinding = BindingOperations.GetMultiBinding(element, dependencyProperty);
                    if (multiBinding != null)
                    {
                        var locStringBinding = ((Binding)multiBinding.Bindings[0]);
                        ProcessSimpleBinding(locStringBinding, element);
                    }
                }
            }
        }

        private bool ProcessSimpleBinding(Binding binding, DependencyObject element)
        {
            if (binding == null) return false;
            if (binding.Source != LocalizationManager.Instance) return false;
            string path = binding.Path.Path;
            if (!path.StartsWith("[")) return false;
            if (!path.EndsWith("]")) return false;
            if (path.Length <= 2) return false;

            string key = path.Substring(1, path.Length - 2);
            strings.Add(new LocalizationString(key, element));
            return true;
        }

        private ObservableCollection<LocalizationString> strings = new ObservableCollection<LocalizationString>();
        private ReadOnlyObservableCollection<LocalizationString> stringsRO;

        public INotifyCollectionChanged Strings
        {
            get { return stringsRO; }
        }

        private System.Collections.ObjectModel.ObservableCollection<Window> windows = new ObservableCollection<Window>();
        private System.Collections.ObjectModel.ReadOnlyObservableCollection<Window> windowsRO;

        public INotifyCollectionChanged Windows
        {
            get { return windowsRO; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void Resume_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var locString = button.DataContext as LocalizationString;
            locString.Resume();
        }
    }
}